//
//  UIViewController+ViewControllerRunTime.m
//  VIVAT
//
//  Created by 韩丛旸 on 16/4/26.
//  Copyright © 2016年 AnBang. All rights reserved.
//

#import "UIViewController+ViewControllerRunTime.h"
#import <objc/runtime.h>

#import "HYLogger.h"

@implementation UIViewController (ViewControllerRunTime)

+ (void)load{

    //方法交换应该被保证，在程序中只会执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //获得viewController的生命周期方法的selector
        SEL systemSel = @selector(viewWillAppear:);
        //自己实现的将要被交换的方法的selector
        SEL swizzSel = @selector(hy_viewWillAppear:);
        //两个方法的Method
        Method systemMethod = class_getInstanceMethod([self class], systemSel);
        Method swizzMethod = class_getInstanceMethod([self class], swizzSel);
        //首先动态添加方法，实现是被交换的方法，返回值表示添加成功还是失败
        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));
        if (isAdd) {
            //如果成功，说明类中不存在这个方法的实现
            //将被交换方法的实现替换到这个并不存在的实现
            class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        }else{
            //否则，交换两个方法的实现
            method_exchangeImplementations(systemMethod, swizzMethod);
        }
    });
}
- (void)hy_viewWillAppear:(BOOL)animated{
    //这时候调用自己，看起来像是死循环
    //但是其实自己的实现已经被替换了

    if (![self isKindOfClass:[UIAlertController class]]
        && ![self isKindOfClass:[UINavigationController class]]
        && ![NSStringFromClass([self class]) isEqualToString:@"UIApplicationRotationFollowingControllerNoTouches"]
        && ![NSStringFromClass([self class]) isEqualToString:@"UIApplicationRotationFollowingController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"UICompatibilityInputViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"UIKeyboardCandidateGridCollectionViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"UIInputWindowController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"HomeViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"ProductViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"JHServiceViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"JHShakeViewController"]
        && ![NSStringFromClass([self class]) isEqualToString:@"UserViewController"]) {
        if ([HYLogger sharedInstance].isRuntimeLogEffective) {
            HYLogDebug(@"*************ViewController*************\n当前的控制器为 %@\n****************************************", [self class]);
        }

    }

    [self hy_viewWillAppear:animated];
    //    NSLog(@"swizzle");
}

@end
